<?php
/**
 * ECSHOP OPEN API统一接口
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: sxc_shop $
 * $Id: goods.php 15921 2009-05-07 05:35:58Z sxc_shop $
*/

define('IN_ECS', true);
unlink('./mobile/admin/data/static/qrimg/1460449557_hongbao_qr.png');
require(dirname(__FILE__) . '/includes/init.php');

require(ROOT_PATH . 'includes/lib_license.php');
require_once('includes/cls_json.php');
$configurl = $db->getOne("select cfg_value from wxch_cfg where cfg_name = 'baseurl'");
$_POST = array_merge($_POST,$_GET);
define('RETURN_TYPE', empty($_POST['return_data']) ? 1 : ($_POST['return_data'] == 'json' ? 2 : 1));
/* 接收传递参数并初步检验 */
if (empty($_POST) || empty($_POST['act']))
{
    api_err('0x003', 'no parameter');   //输出系统级错误:数据异常
}

 $version = '1.0';   //版本号

if ($_POST['api_version'] != $version)      //网店的接口版本低
{
    api_err('0x008', 'a low version api');
}

/* 根据请求类型进入相应的接口处理程序 */
switch ($_POST['act'])
{
    case 'search_goods_list': search_goods_list(); break;
    case 'search_goods_detail': search_goods_detail(); break;
    case 'search_deleted_goods_list': search_deleted_goods_list(); break;
    case 'search_products_list': search_products_list(); break;
    case 'search_site_info': search_site_info(); break;
    case 'inredpacket': inredpacket(); break;
    case 'getredpacket': getredpacket(); break;
    case 'send_redpacket_by_print':send_redpacket_by_print();break;
    case 'send_redpacket_by_user':send_redpacket_by_user();break;
    case 'send_redpacket_goods':send_redpacket_goods();break;
    case 'bonus_to_hongbao':bonus_to_hongbao();break;
    default: api_err('0x008', 'no this type api');   //输出系统级错误:数据异常
}


/**
 *  获取商品列表接口函数
 */
function search_goods_list()
{
    check_auth();   //检查基本权限



    if (is_numeric($_POST['last_modify_st_time']) && is_numeric($_POST['last_modify_en_time']))
    {
        $sql = 'SELECT COUNT(*) AS count' .
               ' FROM ' . $GLOBALS['ecs']->table('goods') .
               " WHERE is_delete = 0 AND is_on_sale = 1 AND (last_update > '" . $_POST['last_modify_st_time'] . "' OR last_update = 0)";
        $date_count = $GLOBALS['db']->getRow($sql);

        if (empty($date_count))
        {
            api_err('0x003', 'no data to back');    //无符合条件数据
        }

        $page = empty($_POST['pages']) ? 1 : $_POST['pages'];       //确定读取哪些记录
        $counts = empty($_POST['counts']) ? 100 : $_POST['counts'];

        $sql = 'SELECT goods_id, last_update AS last_modify' .
               ' FROM ' . $GLOBALS['ecs']->table('goods') .
               " WHERE is_delete = 0 AND is_on_sale = 1 AND (last_update > '" . $_POST['last_modify_st_time'] . "' OR last_update = 0)".
               " LIMIT ".($page - 1) * $counts . ', ' . $counts;
        $date_arr = $GLOBALS['db']->getAll($sql);

        if (!empty($_POST['columns']))
        {
            $column_arr = explode('|', $_POST['columns']);
            foreach ($date_arr as $k => $v)
            {
                foreach ($v as $key => $val)
                {
                    if (in_array($key, $column_arr))
                    {
                        $re_arr['data_info'][$k][$key] = $val;
                    }
                }
            }
        }
        else
        {
            $re_arr['data_info'] = $date_arr;
        }

        /* 处理更新时间等于0的数据 */
        $sql = 'UPDATE ' . $GLOBALS['ecs']->table('goods') .
               " SET last_update = 1 WHERE is_delete = 0 AND is_on_sale = 1 AND last_update = 0";
        $GLOBALS['db']->query($sql, 'SILENT');

        $re_arr['counts'] = $date_count['count'];
        data_back($re_arr, '', RETURN_TYPE);  //返回数据
    }
    else
    {
        api_err('0x003', 'required date invalid');   //请求数据异常
    }
}

/**
 *  商品详细信息接口函数
 */
function search_goods_detail()
{
    check_auth();   //检查基本权限

    $version = '1.0';   //版本号

    if ($_POST['api_version'] != $version)      //网店的接口版本低
    {
        api_err('0x008', 'a low version api');
    }

    if (!empty($_POST['goods_id']) && is_numeric($_POST['goods_id']))
    {
        $sql = 'SELECT g.goods_id, g.last_update AS last_modify, g.cat_id, c.cat_name AS category_name, g.brand_id, b.brand_name, g.shop_price AS price, g.goods_sn AS bn, g.goods_name AS name, g.is_on_sale AS marketable, g.goods_weight AS weight, g.goods_number AS store , g.give_integral AS score, g.add_time AS uptime, g.original_img AS image_default, g.goods_desc AS intro' .
        ' FROM ' . $GLOBALS['ecs']->table('category') . ' AS c, ' . $GLOBALS['ecs']->table('goods') . ' AS g LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON g.brand_id = b.brand_id'.
        ' WHERE g.cat_id = c.cat_id AND g.goods_id = ' . $_POST['goods_id'];
        $goods_data = $GLOBALS['db']->getRow($sql);

        if (empty($goods_data))
        {
            api_err('0x003', 'no data to back');    //无符合条件数据
        }

        $goods_data['goods_link'] = 'http://' . $_SERVER['HTTP_HOST'] . '/goods.php?id=' . $goods_data['goods_id'];
        $goods_data['image_default'] = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $goods_data['image_default'];
        $goods_data['unit'] = '千克';
        $goods_data['brand_name'] = empty($goods_data['brand_name']) ? '' : $goods_data['brand_name'];

        $prop = create_goods_properties($_POST['goods_id']);
        $goods_data['props_name'] = $prop['props_name'];
        $goods_data['props'] = $prop['props'];

        if (!empty($_POST['columns']))
        {
            $column_arr = explode('|', $_POST['columns']);
            foreach ($goods_data as $key=>$val)
            {
                if (in_array($key, $column_arr))
                {
                    $re_arr['data_info'][$key] = $val;
                }
            }
        }
        else
        {
            $re_arr['data_info'] = $goods_data;
        }

        data_back($re_arr, '', RETURN_TYPE);  //返回数据
    }
    else
    {
        api_err('0x003', 'required date invalid');   //请求数据异常
    }
}

/**
 *  被删除商品列表接口函数
 */
function search_deleted_goods_list()
{
    api_err('0x007', '暂时不提供此服务功能');   //服务不可用
}

/**
 *  获取货品列表接口函数
 */
function search_products_list()
{
    check_auth();   //检查基本权限

    $version = '1.0';   //版本号

    if ($_POST['api_version'] != $version)      //网店的接口版本低
    {
        api_err('0x008', 'a low version api');
    }

    if (!empty($_POST['goods_id']) && is_numeric($_POST['goods_id']) || !empty($_POST['bn']))
    {
        $sql = 'SELECT goods_id, last_update AS last_modify, shop_price AS price, goods_sn AS bn, goods_name AS name,  goods_weight         AS weight, goods_number AS store, add_time AS uptime' .
               ' FROM ' . $GLOBALS['ecs']->table('goods') .
               ' WHERE ' . empty($_POST['bn']) ? "goods_id = $_POST[goods_id]" : "goods_sn = $_POST[bn]";
        $goods_data = $GLOBALS['db']->getRow($sql);

        if (empty($goods_data))
        {
            api_err('0x003', 'no data to back');    //无符合条件数据
        }

        $goods_data['product_id'] = $_POST['goods_id'];
        $goods_data['cost'] = $goods_data['price'];

        $prop = create_goods_properties($_POST['goods_id']);
        $goods_data['props'] = $prop['props'];

        if (!empty($_POST['columns']))
        {
            $column_arr = explode('|', $_POST['columns']);
            foreach ($goods_data as $key=>$val)
            {
                if (in_array($key, $column_arr))
                {
                    $re_arr['data_info'][$key] = $val;
                }
            }
        }
        else
        {
            $re_arr['data_info'] = $goods_data;
        }

        data_back($re_arr, '', RETURN_TYPE);  //返回数据
    }
    else
    {
        api_err('0x003', 'required date invalid');   //请求数据异常
    }
}

/**
 *  获取站点信息接口函数
 */
function search_site_info()
{
    check_auth();   //检查基本权限

    $version = '1.0';   //版本号

    if ($_POST['api_version'] != $version)      //网店的接口版本低
    {
        api_err('0x008', 'a low version api');
    }

    $sql = 'SELECT code, value'.
           ' FROM ' . $GLOBALS['ecs']->table('shop_config') .
           " WHERE code IN ('shop_name', 'service_phone')";

    $siteinfo['data_info'] = $GLOBALS['db']->getRow($sql);

    $siteinfo['data_info']['site_address'] = $_SERVER['SERVER_NAME'];

    data_back($siteinfo, '', RETURN_TYPE);  //返回数据
}

/**
 *  权限校验函数
 */
function check_auth()
{


    if (!check_shopex_ac($_POST))
    {
        api_err('0x009');   //输出系统级错误:签名无效
    }


}

/**
 *  验证POST签名
 *
 *  @param   string   $post_params   POST传递参数
 *  @param   string   $token         证书加密码
 *
 *  @return  boolean                 返回是否有效
 */
function check_shopex_ac($post_params)
{
    return true;
    ksort($post_params);
    $str = '';
    foreach($post_params as $key=>$value)
    {
        if ($key!='ac')
        {
            $str.=$value;
        }
    }
    if ($post_params['ac'] == md5($str))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 *  系统级错误处理
 *
 *  @param   string   $err_type   错误类型代号
 *  @param   string   $err_info   错误说明
 *
 */
function api_err($err_type, $err_info = '')
{
    /* 系统级错误列表 */
    $err_arr = array();
    $err_arr['0x001'] = 'Verify fail';          //身份验证失败
    $err_arr['0x002'] = 'Time out';             //请求/执行超时
    $err_arr['0x003'] = 'Data fail';            //数据异常
    $err_arr['0x004'] = 'Db error';             //数据库执行失败
    $err_arr['0x005'] = 'Service error';        //服务器导常
    $err_arr['0x006'] = 'User permissions';     //用户权限不够
    $err_arr['0x007'] = 'Service unavailable';  //服务不可用
    $err_arr['0x008'] = 'Missing Method';       //方法不可用
    $err_arr['0x009'] = 'Missing signature';    //签名无效
    $err_arr['0x010'] = 'Missing api version';  //版本丢失
    $err_arr['0x011'] = 'Api verion error';     //API版本异常
    $err_arr['0x012'] = 'Api need update';      //API需要升级
    $err_arr['0x013'] = 'Shop Error';           //网痁服务异常
    $err_arr['0x014'] = 'Shop Space Error';     //网店空间不足

    data_back($err_info == '' ? $err_arr[$err_type] : $err_info, $err_type, RETURN_TYPE, 'fail');  //回复请求以错误信息
}

/**
 *  返回结果集
 *
 *  @param   mixed      $info       返回的有效数据集或是错误说明
 *  @param   string     $msg        为空或是错误类型代号
 *  @param   string     $result     请求成功或是失败的标识
 *  @param   int        $post       1为xml方式，2为json方式
 *
 */
function data_back($info, $msg = '', $post, $result = 'success')
{
    /* 分为xml和json两种方式 */
    $data_arr = array('result'=>$result, 'msg'=>$msg, 'info'=>$info);
    $data_arr = to_utf8_iconv($data_arr);  //确保传递的编码为UTF-8

    if ($post == 1)
    {
        /* xml方式 */
        if (class_exists('DOMDocument'))
        {
            $doc=new DOMDocument('1.0','UTF-8');
            $doc->formatOutput=true;

            $shopex=$doc->createElement('guanyi');
            $doc->appendChild($shopex);

            $result=$doc->createElement('result');
            $shopex->appendChild($result);
            $result->appendChild($doc->createCDATASection($data_arr['result']));

            $msg=$doc->createElement('msg');
            $shopex->appendChild($msg);
            $msg->appendChild($doc->createCDATASection($data_arr['msg']));

            $info=$doc->createElement('info');
            $shopex->appendChild($info);

            create_tree($doc, $info, $data_arr['info']);
            die($doc->saveXML());
        }

        die('<?xml version="1.0" encoding="UTF-8"?>' . array2xml($data_arr)) ;
    }
    else
    {
        /* json方式 */
        $json  = new JSON;
        die($json->encode($data_arr));    //把生成的返回字符串打印出来
    }
}

/**
 *  循环生成xml节点
 *
 *  @param  handle      $doc            xml实例句柄
 *  @param  handle      $top            当前父节点
 *  @param  array       $info_arr       需要解析的数组
 *  @param  boolean     $have_item      是否是数据数组，是则需要在每条数据上加item父节点
 *
 */
function create_tree($doc, $top, $info_arr, $have_item = false)
{
    if (is_array($info_arr))
    {
        foreach ($info_arr as $key => $val)
        {
            if (is_array($val))
            {
                if ($have_item == false)
                {
                    $data_info=$doc->createElement('data_info');
                    $top->appendChild($data_info);
                    create_tree($doc, $data_info, $val, true);
                }
                else
                {
                    $item=$doc->createElement('item');
                    $top->appendChild($item);
                    $key_code = $doc->createAttribute('key');
                    $item->appendChild($key_code);
                    $key_code->appendChild($doc->createTextNode($key));
                    create_tree($doc, $item, $val);
                }
            }
            else
            {
                $text_code=$doc->createElement($key);
                $top->appendChild($text_code);
                if (is_string($val))
                {
                    $text_code->appendChild($doc->createCDATASection($val));
                }
                else
                {
                    $text_code->appendChild($doc->createTextNode($val));
                }
            }
        }
    }
    else
    {
        $top->appendChild($doc->createCDATASection($info_arr));
    }
}

function array2xml($data,$root='guanyi'){
    $xml='<'.$root.'>';
    _array2xml($data,$xml);
    $xml.='</'.$root.'>';
    return $xml;
}

function _array2xml(&$data,&$xml){
    if(is_array($data)){
        foreach($data as $k=>$v){
            if(is_numeric($k)){
                $xml.='<item key="' . $k . '">';
                $xml.=_array2xml($v,$xml);
                $xml.='</item>';
            }else{
                $xml.='<'.$k.'>';
                $xml.=_array2xml($v,$xml);
                $xml.='</'.$k.'>';
            }
        }
    }elseif(is_numeric($data)){
        $xml.=$data;
    }elseif(is_string($data)){
        $xml.='<![CDATA['.$data.']]>';
    }
}

function create_goods_properties($goods_id)
{
    /* 对属性进行重新排序和分组
    $sql = "SELECT attr_group ".
            "FROM " . $GLOBALS['ecs']->table('goods_type') . " AS gt, " . $GLOBALS['ecs']->table('goods') . " AS g ".
            "WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type";
    $grp = $GLOBALS['db']->getOne($sql);

    if (!empty($grp))
    {
        $groups = explode("\n", strtr($grp, "\r", ''));
    }
    */

    /* 获得商品的规格 */
    $sql = "SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, ".
                "g.goods_attr_id, g.attr_value, g.attr_price " .
            'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' .
            "WHERE g.goods_id = '$goods_id' " .
            'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array();
    $arr['props_name'] = array();     // props_name
    $arr['props'] = array();          // props

    foreach ($res AS $row)
    {
        if ($row['attr_type'] == 0)
        {
            //$group = (isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : $GLOBALS['_LANG']['goods_attr'];

            //$arr['props_name'][$row['attr_group']]['name'] = $group;
            $arr['props_name'][] = array('name' => $row['attr_name'], 'value' => $row['attr_value']);

            $arr['props'][] = array('pid' => $row['attr_id'], 'vid' => $row['goods_attr_id']);
        }
    }

    return $arr;
}
function getredpacket(){
    $sql = "SELECT bonus_type_id, COUNT(*) AS sent_count".
            " FROM " .$GLOBALS['ecs']->table('user_bonus') .
            " GROUP BY bonus_type_id";
    $res = $GLOBALS['db']->query($sql);

    $sent_arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $sent_arr[$row['bonus_type_id']] = $row['sent_count'];
    }

    /* 获得所有红包类型的发放数量 */
    $sql = "SELECT bonus_type_id, COUNT(*) AS used_count".
            " FROM " .$GLOBALS['ecs']->table('user_bonus') .
            " WHERE used_time > 0".
            " GROUP BY bonus_type_id";
    $res = $GLOBALS['db']->query($sql);

    $used_arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $used_arr[$row['bonus_type_id']] = $row['used_count'];
    }
    $filter['page_size'] = $_REQUEST['pagesize']?$_REQUEST['pagesize']:10;
    $filter['page'] = $filter['page']?$filter['page']:1;
    $filter['start'] = ($filter['page']-1)*$filter['page_size'];
    $result = false;
    $where = array(1);
    if ($result === false)
    {
        /* 查询条件 */
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'type_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('bonus_type');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        if($_REQUEST['type_id']){
            $where[] = ' type_id ='.$_REQUEST['type_id'];
        }
        /* 分页大小 */

        $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('bonus_type'). " where ".implode(' AND ',$where). " ORDER BY $filter[sort_by] $filter[sort_order]";

    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['send_by'] = $GLOBALS['_LANG']['send_by'][$row['send_type']];
        $row['send_count'] = isset($sent_arr[$row['type_id']]) ? $sent_arr[$row['type_id']] : 0;
        $row['use_count'] = isset($used_arr[$row['type_id']]) ? $used_arr[$row['type_id']] : 0;

        $arr[] = $row;
    }

    $arr = array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    data_back($arr, '', RETURN_TYPE);  //返回数据
}
function admin_log($sn = '', $action, $content)
{
    $log_info = $GLOBALS['_LANG']['log_action'][$action] . $GLOBALS['_LANG']['log_action'][$content] .': '. addslashes($sn);

    $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('admin_log') . ' (log_time, user_id, log_info, ip_address) ' .
            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . stripslashes($log_info) . "', '" . real_ip() . "')";
    $GLOBALS['db']->query($sql);
}
function inredpacket(){
    $_POST['type_name'] = '线下红包1';//类型名称
    $_POST['type_money'] = '5.00';//红包金额
    $_POST['min_goods_amount'] = '360.00';//最小订单金额
    $_POST['send_type'] = 0;//红包类型 0:按用户发放;1:按商品发放;2:按订单金额发放;3:线下发放的红包
    $_POST['send_start_date'] = '2009-05-12';//发放起始日期
    $_POST['send_end_date'] = '2009-05-12';//发放结束日期
    $_POST['use_start_date'] = '2009-05-12';//使用起始日期
    $_POST['use_end_date'] = '2009-05-12';//使用结束日期
    check_auth();   //检查基本权限
    /* 去掉红包类型名称前后的空格 */
    $type_name   = !empty($_POST['type_name']) ? trim($_POST['type_name']) : '';

    /* 初始化变量 */
    $type_id     = !empty($_POST['type_id'])    ? intval($_POST['type_id'])    : 0;
    $min_amount  = !empty($_POST['min_amount']) ? intval($_POST['min_amount']) : 0;

    /* 检查类型是否有重复 */
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('bonus_type'). " WHERE type_name='$type_name'";
    if ($GLOBALS['db']->getOne($sql) > 0)
    {
        data_back(0, 'type_name is exists', RETURN_TYPE);  //返回数据
    }

    /* 获得日期信息 */
    $send_startdate = local_strtotime($_POST['send_start_date']);
    $send_enddate   = local_strtotime($_POST['send_end_date']);
    $use_startdate  = local_strtotime($_POST['use_start_date']);
    $use_enddate    = local_strtotime($_POST['use_end_date']);

    /* 插入数据库。 */
    $sql = "INSERT INTO ".$GLOBALS['ecs']->table('bonus_type')." (type_name, type_money,send_start_date,send_end_date,use_start_date,use_end_date,send_type,min_amount,min_goods_amount)
    VALUES ('$type_name',
            '$_POST[type_money]',
            '$send_startdate',
            '$send_enddate',
            '$use_startdate',
            '$use_enddate',
            '$_POST[send_type]',
            '$min_amount','" . floatval($_POST['min_goods_amount']) . "')";

    $GLOBALS['db']->query($sql);
    $type_id = $GLOBALS['db']->insert_id();
    /* 记录管理员操作 */
    admin_log('api', 'add', 'bonustype');
    data_back($type_id, 'success', RETURN_TYPE);  //返回数据
}
//按线下发送红包
function send_redpacket_by_print()
{
    if(!$_POST['type_id'] || !$_POST['bonus_sum']){
        api_err('0x003', 'no parameter');
    }
    @set_time_limit(0);

    /* 红下红包的类型ID和生成的数量的处理 */
    $bonus_typeid = $_POST['type_id'];
    $bonus_sum    = $_POST['bonus_sum'];

    /* 生成红包序列号 */
    $num = $GLOBALS['db']->getOne("SELECT MAX(bonus_sn) FROM ". $ecs->table('user_bonus'));
    $num = $num ? floor($num / 10000) : 100000;

    for ($i = 0, $j = 0; $i < $bonus_sum; $i++)
    {
        $bonus_sn = ($num + $i) . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $GLOBALS['db']->query("INSERT INTO ".$GLOBALS['ecs']->table('user_bonus')." (bonus_type_id, bonus_sn) VALUES('$bonus_typeid', '$bonus_sn')");

        $j++;
    }

    /* 记录管理员操作 */
    admin_log($bonus_sn, 'add', 'userbonus');

    data_back(array(), 'success', RETURN_TYPE);  //返回数据
}
//按用户发送红包
function send_redpacket_by_user()
{
    $json  = new JSON;
    if(!$_POST['userlist'] || !$_POST['type_id']){
        api_err('0x003', 'no parameter');
    }

    $user_list  = $json->decode($_POST['userlist']);

    /* 发送红包 */
    $loop       = 0;
    $bonus_type = bonus_type_info($_REQUEST['type_id']);

    foreach ($user_list AS $key => $user_id)
    {

             /* 向会员红包表录入数据 */
            $sql = "INSERT INTO " . $GLOBALS['ecs']->table('user_bonus') .
                    "(bonus_type_id, bonus_sn, user_id, used_time, order_id, emailed) " .
                    "VALUES ('$_REQUEST[type_id]', 0, '$user_id', 0, 0,0)";
            $GLOBALS['db']->query($sql);
    }
    data_back(array(), 'success', RETURN_TYPE);  //返回数据

}
//按商品发红包
function send_redpacket_goods(){
    $json  = new JSON;
    if(!$_POST['add_ids'] || !$_POST['type_id']){
        api_err('0x003', 'no parameter');
    }
    $add_ids    = $json->decode($_POST['add_ids']);
    $type_id    = $_POST['type_id'];

    foreach ($add_ids AS $key => $val)
    {
        $sql = "UPDATE " .$GLOBALS['ecs']->table('goods'). " SET bonus_type_id='$type_id' WHERE goods_id='$val'";
        $GLOBALS['db']->query($sql, 'SILENT');
    }
    data_back(array(), 'success', RETURN_TYPE);  //返回数据
}
/**
 * 取得红包类型信息
 * @param   int     $bonus_type_id  红包类型id
 * @return  array
 */
function bonus_type_info($bonus_type_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('bonus_type') .
            " WHERE type_id = '$bonus_type_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 添加（抢）红包信息
 * @param   int     $bao_money  红包金额
 * @param   int     $bao_num  红包数量
 * @param   int     $max_money  红包最大额度
 * @param   int     $min_money  红包最少额度
 * @return  array
 */
function bonus_to_hongbao()
{
    global $configurl;
    $bao_money = $_GET['bao_money'];
    $bao_num = intval($_GET['bao_num']);
    $max_money = $_POST['max_money'];
    $min_money = $_POST['min_money'];
    // $user_id = $_SEESION['user_id'];
    $add_time = time();
    if(!empty($bao_money) && !empty($bao_num)){
        
        $sql = "insert into " . $GLOBALS['ecs']->table("user_bao") . " ( bao_money, bao_num, add_time) values ('$bao_money','$bao_num','$add_time')";

        if($rr = $GLOBALS['db']->query($sql))
        {
            $bao_id = mysql_insert_id();
            
            $url = $configurl .'mobile/to_hongbao.php?act=edit&bao_id='.mysql_insert_id();
            $logo_qr  = qr($url);
            $GLOBALS['db']->query("UPDATE ". $GLOBALS['ecs']->table("user_bao") ." set bao_qr = '".$logo_qr."' where bao_id = '".mysql_insert_id()."'");
            $sql = "select bao_id from " . $GLOBALS['ecs']->table("user_bao") . "where add_time = ".$add_time;

            $bao_id = $GLOBALS['db'] -> getOne($sql);

            // 分配红包，调用tobonus函数
            // $arrs = getBonus($bao_money,$bao_num,$max_money,$min_money);
            $arrs = sendRandBonus($bao_money,$bao_num);
            if($arrs){
                // 分配好的红包，分别插入数据库
                foreach ($arrs as $key => $value) {
                    $sql = "insert into " . $GLOBALS['ecs']->table("user_bao_one") . " ( bao_id, one_money)  values ('$bao_id', ' " . $value . " ')";
                    if($GLOBALS['db']->query($sql)){
                        
                    }
                }
            }
        }
    }

    $hongbao_info = bonus_to_qr_info($bao_id);
    data_back($hongbao_info, 'success', 2);  //返回数据
}

/**
 * 发送红包二维码信息
 * @param   int     $bao_id  红包id
 * @return  array
 */
function bonus_to_qr_info($bao_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_bao') .
            " WHERE bao_id = '$bao_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 生成红包二维码
 * @param $value 二维码内容
 * @param $errorCorrectionLevel 容错级别
 * @param $matrixPointSize 生成图片大小
 * @return 生成n个红包 array() 
 **/
function qr($value, $errorCorrectionLevel = 'M', $matrixPointSize= 10){
    global $configurl;
    require(dirname(__FILE__) . '/mobile/admin/includes/phpqrcode/phpqrcode.php');
    $time = time();
    // $value = $config['site_url'].'mobile/to_hongbao.php?act=edit'; //二维码内容 
    // $errorCorrectionLevel = 'M';//容错级别 
    // $matrixPointSize = 10;//生成图片大小 
    //生成二维码图片 
    // $road = '/mobile/images/qrimg/'.time().'.png';
    // $QR = './shop/mobile/admin/qrcode.png';
    $QR = './mobile/admin/data/static/qrimg/'.time().'_hongbao_qr.png';
    QRcode::png($value, $QR, $errorCorrectionLevel, $matrixPointSize, 2); 
    $logo = './mobile/admin/data/static/images/logo.png';//准备好的logo图片 
    //已经生成的原始二维码图 

    if ($logo !== FALSE) { 
        $QR = imagecreatefromstring(file_get_contents($QR)); 
        $logo = imagecreatefromstring(file_get_contents($logo)); 
        $QR_width = imagesx($QR);//二维码图片宽度 
        $QR_height = imagesy($QR);//二维码图片高度 
        $logo_width = imagesx($logo);//logo图片宽度 
        $logo_height = imagesy($logo);//logo图片高度 
        $logo_qr_width = $QR_width / 5; 
        $scale = $logo_width/$logo_qr_width; 
        $logo_qr_height = $logo_height/$scale; 
        $from_width = ($QR_width - $logo_qr_width) / 2; 
        //重新组合图片并调整大小 
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, 
        $logo_qr_height, $logo_width, $logo_height); 
    } 
    //输出图片 
    $road = './mobile/admin/data/static/qrimg/'.$time.'_water_qr.png';
    imagepng($QR, $road);
    return str_replace('/mobile/admin/', '/', $road); 
}

// $total 红包总金额
// $count 红包个数
// $type 红包类型 1=拼手气红包 0=普通红包
function sendRandBonus($total=0, $count=3, $type=1){
  if($type==1){
    $input     = range(0.01, $total, 0.01);
    if($count>1){
      $rand_keys = (array) array_rand($input, $count-1);
      $last    = 0;
      foreach($rand_keys as $i=>$key){
        $current  = $input[$key]-$last;
        $items[]  = $current;
        $last    = $input[$key];
      }
    }
    $items[]    = $total-array_sum($items);
  }else{
    $avg      = number_format($total/$count, 2);
    $i       = 0;
    while($i<$count){
      $items[]  = $i<$count-1?$avg:($total-array_sum($items));
      $i++;
    }
  }
  return $items;
}
?>